CFLAGS = -g

PRODUCT_NAMES = MonsterSymbol.java Color.java MonsterAttack.java Flag.java Generation.java \
				Race.java Resistance.java Size.java Sound.java
PROGRAM_NAMES = attack monstp monsym colors monflag

PARSER_MAPPING = MonsterSymbol.java/monsym Color.java/colors MonsterAttack.java/attack Flag.java/monflag \
				Generation.java/monflag Race.java/monflag Resistance.java/monflag Size.java/monflag Sound.java/monflag
SOURCE_MAPPING = MonsterSymbol.java/monsym.h Color.java/color.h MonsterAttack.java/monattk.h Flag.java/monflag.h \
				Generation.java/monflag.h Race.java/monflag.h Resistance.java/monflag.h Size.java/monflag.h Sound.java/monflag.h 

MONSTER_DIR = ../src/termint/game/monsters/
BIN_DIR = ./bin
NHSRC_DIR = ./nhsrc

BISON_FILES := $(foreach prog, $(PROGRAM_NAMES), $(prog).tab.h $(prog).tab.c)
COMPILED_FILES := $(foreach prog, $(PROGRAM_NAMES), $(prog).tab.o $(prog).yy.o)
PROGRAMS := $(foreach prog, $(PROGRAM_NAMES), $(BIN_DIR)/$(prog))
PRODUCT := $(foreach prod, $(PRODUCT_NAMES), $(MONSTER_DIR)$(prod))

# usage:  $(call lookup,$key,$mapping)
# where $mapping = key/value  key2/val2 ...
# doesn't enforce uniqueness, and you'll probably die if it's not unique...
lookup = $(notdir $(filter $(1)%,$(2)))

.PHONY: all clean monsters other_java
.INTERMEDIATE: $(BISON_FILES) $(COMPILED_FILES)
.SECONDEXPANSION:

all: other_java monsters

other_java: $(PRODUCT)
	$(if $(shell ls *.java), \
	for j in $(PRODUCT_NAMES); do \
		mv -v $$j $(MONSTER_DIR); \
	done, \
	@echo up to date)

clean:
	-rm -fr $(BIN_DIR)/* $(PRODUCT)
	-rm -f *.o
	-rm -f $(MONSTER_DIR)all/*.java

%.tab.c %.tab.h : %.y
	bison -d --output=$@ $<

%.yy.c : %.l %.tab.h
	flex --outfile=$@ $<

$(PROGRAMS): $$(notdir $$@.tab.o) $$(notdir $$@.yy.o)
	$(CC) $(LDFLAGS) $^ -o $@
	
monsters: $(BIN_DIR)/monstp
	$(if $(shell ls *.java), $(error Loose .java files in directory.  Remove them.))
	$(BIN_DIR)/monstp
	mv -v *.java ../src/termint/game/monsters/all/

# how cool is this abuse of gnumake?
# For each element of PRODUCT, there must be a matching element in both PARSER_MAPPING and SOURCE_MAPPING
# (allthough you could make the source one null, as in "Bla.java/")
$(PRODUCT): $(BIN_DIR)/$$(call lookup, $$(notdir $$@), $(PARSER_MAPPING)) $(NHSRC_DIR)/$$(call lookup, $$(notdir $$@), $(SOURCE_MAPPING))
	$<
